<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisble" :before-close="handleClose" :close-on-click-modal=false
               width="35%">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="100px">

        <el-form-item label="连接名" prop="name">
          <el-input v-model="dataForm.name" maxlength="50" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="类型" prop="dbType">
          <el-select v-model="dataForm.dbType" placeholder="请选择数据源类型">
            <el-option label="mysql" value="mysql"></el-option>
            <el-option label="clickhouse" value="clickhouse" show-word-limit></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="主机" prop="host">
          <el-input v-model="dataForm.host" maxlength="50" minlength="10" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="端口" prop="port">
          <el-input v-model="dataForm.port" maxlength="20" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="账号" prop="username">
          <el-input v-model="dataForm.username" maxlength="50" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="dataForm.password" autocomplete="off" maxlength="50" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="数据库名" prop="dbName">
          <el-input v-model="dataForm.dbName" maxlength="50" show-word-limit></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">
          取消
        </el-button>
        <el-button type="primary" @click="testConnect('dataForm')" v-permission="'dataSource:test'">
          测试连接
        </el-button>
        <el-button type="primary" @click="save()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  testConnectApi,
  createDataSourceApi,
  updateDataSourceApi,
} from '@/api/api'
import {SM4Util} from "@/utils/sm4";

const sm4 = new SM4Util();
export default {
  name: "dataSourceForm",
  props: ["dialogVisble", "title", "editData"],
  data() {
    return {
      dialogStatus: "",
      dataForm: {
        name: '',
        dbType: '',
        host: '',
        username: '',
        password: '',
        port: '',
        dbName: ''
      },
      rules: {
        name: [{required: true, message: '请输入连接名', trigger: 'blur'}],
        dbType: [{required: true, message: '请选择类型', trigger: 'change'}],
        host: [
          {required: true, message: '主机不能为空', trigger: 'blur'},
          {min: 10, max: 50, message: '主机长度在 10 到 50 个字符', trigger: 'blur'}
        ],
        username: [{required: true, message: '请输入账号', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        port: [{required: true, message: '请输入端口', trigger: 'blur'}],
        dbName: [{required: true, message: '请输入数据库名', trigger: 'blur'}]
      },
    }
  },
  methods: {
    /*更新本组件对话框状态*/
    handleClose() {
      this.$emit("closeDialog")
    },

    /*新建、编辑*/
    save() {
      console.log("dataForm", this.dataForm)
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (this.title === "新建数据源") {
            this.dataForm.createUser = this.$store.state.user.userId
            let data = {...this.dataForm}
            data.password = sm4.encryptData_CBC(data.password)
            this.api({url: "/addDataSource", method: "post", data: data}).then(resp => {
              this.$emit("refreshList")
              this.$message({message: resp, type: 'success'});
            })
          } else {
            this.dataForm.updateUser = this.$store.state.user.userId
            let data = {...this.dataForm}
            this.api({url: "/updateDataSource", method: "put", data: data}).then(resp => {
              this.$emit("refreshList")
              this.$message({message: resp, type: 'success'});
            })
          }
        }
      })
    },

    /*测试链接*/
    testConnect(dataForm) {
      this.$refs[dataForm].validate(async valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true, // lock的修改符--默认是false
            text: 'Loading', // 显示在加载图标下方的加载文案
            spinner: 'el-icon-loading', // 自定义加载图标类名
            target: document.querySelector('.main')//loading覆盖的dom元素节点
          })
          let data = {...this.dataForm}
          data.password = this.title === "新建数据源" ? sm4.encryptData_CBC(data.password) : data.password
          let resp = await testConnectApi(data)
          if (resp === "测试链接成功") {
            this.$message({message: resp, type: 'success'})
          }
          loading.close()
        }
      })
    }
  },
  watch: {
    editData() {
      this.dataForm = {...this.editData}
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    }
  }
}
</script>

<style scoped>

</style>
